package io.renren.modules.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.constants.BusinessConstants;
import io.renren.common.constants.ExceptionConstants;
import io.renren.common.exception.BusinessRunTimeException;
import io.renren.common.utils.Constants;
import io.renren.common.utils.QueryUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import io.renren.modules.erp.entity.Depot;
import io.renren.modules.erp.entity.DepotEx;
import io.renren.modules.erp.entity.DepotHead;
import io.renren.modules.erp.entity.Sysuser;
import io.renren.modules.erp.service.AccountService;
import io.renren.modules.erp.service.DepotService;
import io.renren.modules.erp.service.MaterialService;
import io.renren.modules.erp.service.SystemConfigService;
import io.renren.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author ji sheng hua 752*718*920
 */
@RestController
@RequestMapping(value = "/depot")
public class DepotController  extends AbstractController {
    private Logger logger = LoggerFactory.getLogger(DepotController.class);

    @Autowired
    private AccountService accountService;
    @Autowired
    private DepotService depotService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private MaterialService materialService;

    @GetMapping(value = "/list")
//    @RequiresPermissions("depot:list")
    public R getAccountList(@RequestParam Map<String, String> params) throws Exception{
        String search = params.get(Constants.SEARCH);
        String name = StringUtil.getInfo(search, "name");
        Integer type = StringUtil.parseInteger(StringUtil.getInfo(search, "type"));
        String remark = StringUtil.getInfo(search, "remark");
        String order = QueryUtils.order(params);
        int pageSize = Integer.valueOf(params.get( "pageSize"));
        int currPage = Integer.valueOf(params.get( "currentPage"));
        return R.ok().put("data",depotService.select(name, type, remark, currPage, pageSize));
    }

    @GetMapping(value = "/getAllList")
//    @RequiresPermissions("depot:getAllList")
    public R getAllList(HttpServletRequest request) throws Exception{
            List<Depot> depotList = depotService.getAllList();
            return R.ok().put("data",depotList);
    }


    @GetMapping(value = "/getAllUser")
//    @RequiresPermissions("depot:getAllList")
    public R getAllUser(HttpServletRequest request) throws Exception{
        List<Sysuser> depotList22 = depotService.getAllUser();
        return R.ok().put("data",depotList22);
    }

    @GetMapping(value = "/getAllSubtype")
//    @RequiresPermissions("depot:getAllList")
    public R getAllSubtype(HttpServletRequest request) throws Exception{
        List<DepotHead> depotList = depotService.getAllSubtype();
        return R.ok().put("data",depotList);
    }


    /**
     * 用户对应仓库显示
     * @param type
     * @param keyId
     * @param request
     * @return
     */
    @PostMapping(value = "/findUserDepot")
    public R findUserDepot(@RequestParam("UBType") String type, @RequestParam("UBKeyId") String keyId,
                                 HttpServletRequest request) throws Exception{
        JSONArray arr = new JSONArray();
            List<Depot> dataList = depotService.findUserDepot();
            //开始拼接json数据
            JSONObject outer = new JSONObject();
            outer.put("id", 1);
            outer.put("text", "仓库列表");
            outer.put("state", "open");
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataList) {
                for (Depot depot : dataList) {
                    JSONObject item = new JSONObject();
                    item.put("id", depot.getId());
                    item.put("text", depot.getName());
                    //勾选判断1
                    Boolean flag = false;
                    //TODO
//                    try {
//                        flag = userBusinessService.checkIsUserBusinessExist(type, keyId, "[" + depot.getId().toString() + "]");
//                    } catch (Exception e) {
//                        logger.error(">>>>>>>>>>>>>>>>>设置用户对应的仓库：类型" + type + " KeyId为： " + keyId + " 存在异常！");
//                    }
//                    if (flag == true) {
                        item.put("checked", true);
//                    }
                    //结束
                    dataArray.add(item);
                }
            }
            outer.put("children", dataArray);
            arr.add(outer);
        return R.ok().put("data",arr);
    }

    /**
     * 获取用户拥有权限的仓库列表
     * @param type
     * @param keyId
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/findDepotByUserId")
    public R findDepotByUserId(@RequestParam("UBType") String type, @RequestParam("UBKeyId") String keyId,
                                       HttpServletRequest request) throws Exception{
        JSONArray arr = new JSONArray();
            List<Depot> dataList = depotService.findUserDepot();
            //开始拼接json数据
            if (null != dataList) {
                boolean depotFlag = systemConfigService.getDepotFlag();
                for (Depot depot : dataList) {
                    JSONObject item = new JSONObject();
                    //勾选判断1
                    Boolean flag = false;
                    //TODO
//                    try {
//                        flag = userBusinessService.checkIsUserBusinessExist(type, keyId, "[" + depot.getId().toString() + "]");
//                    } catch (DataAccessException e) {
//                        logger.error(">>>>>>>>>>>>>>>>>查询用户对应的仓库：类型" + type + " KeyId为： " + keyId + " 存在异常！");
//                    }
                    if (!depotFlag || flag) {
                        item.put("id", depot.getId());
                        item.put("depotName", depot.getName());
                        arr.add(item);
                    }
                }
            }
                return R.ok().put("data",arr);

}

    /**
     *  批量删除仓库信息
     * create time: 2019/3/29 11:15
     * @Param: ids
     * @return java.lang.Object
     */
    @RequestMapping(value = "/batchDeleteDepotByIds")
    public R batchDeleteDepotByIds(@RequestParam("ids") String ids,@RequestParam(value="deleteType",
            required =false,defaultValue= BusinessConstants.DELETE_TYPE_NORMAL)String deleteType) throws Exception {
        JSONObject result = ExceptionConstants.standardSuccess();
        int i=0;
        if(BusinessConstants.DELETE_TYPE_NORMAL.equals(deleteType)){
            i= depotService.batchDeleteDepotByIdsNormal(ids,getUserId());
        }else if(BusinessConstants.DELETE_TYPE_FORCE.equals(deleteType)){
            i= depotService.batchDeleteDepotByIds(ids,getUserId());
        }else{
            logger.error("异常码[{}],异常提示[{}],参数,ids[{}],deleteType[{}]",
                    ExceptionConstants.DELETE_REFUSED_CODE,ExceptionConstants.DELETE_REFUSED_MSG,ids,deleteType);
            throw new BusinessRunTimeException(ExceptionConstants.DELETE_REFUSED_CODE,
                    ExceptionConstants.DELETE_REFUSED_MSG);
        }
        if(i<1){
            logger.error("异常码[{}],异常提示[{}],参数,ids[{}]",
                    ExceptionConstants.DEPOT_DELETE_FAILED_CODE,ExceptionConstants.DEPOT_DELETE_FAILED_MSG,ids);
            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_DELETE_FAILED_CODE,
                    ExceptionConstants.DEPOT_DELETE_FAILED_MSG);
        }
        return R.ok().put("data",result) ;
    }
    @PostMapping(value = "/updateDepotIsDefault")
    public R updateDepotIsDefault(@RequestParam("isDefault") Boolean isDefault,
                                        @RequestParam("depotID") Long depotID,
                                        HttpServletRequest request) throws Exception{
        int res = depotService.updateDepotIsDefault(isDefault, depotID);
        if(res > 0) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @GetMapping(value = "/getAllListWithStock")
    public R getAllList(@RequestParam("mId") Long mId,
                                       HttpServletRequest request) throws Exception {
            List<Depot> list = depotService.getAllList();
            List<DepotEx> depotList = new ArrayList<DepotEx>();
            for(Depot depot: list) {
                DepotEx de = new DepotEx();
                if(mId!=0) {
                    BigDecimal stock = materialService.getInitStock(mId, depot.getId());
                    de.setStock(stock);
                } else {
                    de.setStock(BigDecimal.ZERO);
                }
                de.setId(depot.getId());
                de.setName(depot.getName());
                depotList.add(de);
            }
            return R.ok().put("data",depotList);
    }

    @PostMapping(value = "/add")
    public R insert(@RequestBody String beanJson, HttpServletRequest request) throws Exception{
        if(1== depotService.insertDepot(beanJson, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @PostMapping(value = "/update")
    public R update(@RequestBody String beanJson, Long id, HttpServletRequest request)throws Exception {
        if(1==depotService.updateDepot(beanJson, id, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/delete")
    public R delete(@RequestParam("id")Long id, HttpServletRequest request)throws Exception {
        if(1==depotService.deleteDepot(id, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/batchDelete")
    public R batchDelete(@RequestParam("ids")String ids, HttpServletRequest request)throws Exception {
        if(1==depotService.batchDeleteDepot(ids, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/checkIsNameExist")
    public R checkIsNameExist(@RequestParam("id") Long id, @RequestParam("name") String name)throws Exception {
        if(0<depotService.checkIsNameExist(id, name)){
            return R.ok();
        }else{
            return R.error();
        }
    }
}
